package com.bysj.sausys.service.impl;

import com.bysj.sausys.beans.PageQuery;
import com.bysj.sausys.beans.PageResult;
import com.bysj.sausys.beans.Pagination;
import com.bysj.sausys.common.UserConst;
import com.bysj.sausys.dao.SysUserMapper;
import com.bysj.sausys.exception.ParamException;
import com.bysj.sausys.model.SysUser;
import com.bysj.sausys.service.ISysUserService;
import com.bysj.sausys.util.Md5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户Service
 *
 * @author WangZK
 */
@Service("sysUserService")
public class SysUserServiceImpl implements ISysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 保存系统用户
     *
     * @param sysUser         系统用户实体
     * @param currentUsername 当前用户
     */
    @Override
    public void save(SysUser sysUser, String currentUsername) {
        if (checkUserExist(sysUser.getUsername())) {
            throw new ParamException("用户已存在，保存失败");
        }
        if (StringUtils.isNotEmpty(sysUser.getCategoryId())) {
            if (checkAssociationIdIsNull(sysUser)) {
                throw new ParamException("创建社团管理员，需要关联社团");
            }
        } else {
            throw new ParamException("管理员类型不能为空");
        }
        // TODO:密码暂时设置为123456，之后会随机生成密码并发送到注册邮箱
        String password = "123456";
        // 密码加密
        String encryptedPassword = Md5Util.encrypt(password);
        sysUser.setPassword(encryptedPassword);

        sysUser.setInsertMan(currentUsername);
        sysUser.setInsertTime(new Date());

        sysUserMapper.insertSelective(sysUser);
    }

    /**
     * 判断用户是否已存在
     *
     * @param username
     * @return
     */
    private boolean checkUserExist(String username) {
        return sysUserMapper.countByUsername(username) > 0;
    }

    /**
     * 判断是否需要关联社团
     *
     * @param sysUser 系统用户实体
     * @return
     */
    private boolean checkAssociationIdIsNull(SysUser sysUser) {
        if (UserConst.SHETUANGUANLIYUAN.equals(sysUser.getCategoryId())) {
            if (!(sysUser.getAssId() > 0)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 更新系统用户
     *
     * @param sysUser         系统用户实体
     * @param currentUsername 当前用户
     */
    @Override
    public void update(SysUser sysUser, String currentUsername) {
        SysUser before = sysUserMapper.selectByPrimaryKey(sysUser.getId());
        if (before == null) {
            throw new ParamException("待更新的用户不存在");
        }
        if (StringUtils.isNotEmpty(sysUser.getCategoryId())) {
            if (checkAssociationIdIsNull(sysUser)) {
                throw new ParamException("更新社团管理员，需要关联社团");
            }
        } else {
            throw new ParamException("管理员类型不能为空");
        }
        SysUser after = new SysUser();

        after.setId(sysUser.getId());
        after.setCategoryId(sysUser.getCategoryId());
        after.setAssId(sysUser.getAssId());
        after.setStatus(before.getStatus());
        after.setLastupdMan(currentUsername);
        after.setLastupdTime(new Date());

        sysUserMapper.updateByPrimaryKeySelective(after);
    }

    /**
     * 根据用户类型获取用户信息
     *
     * @param categoryId 用户类型id
     * @param pageQuery  分页查询类
     * @return
     */
    @Override
    public PageResult<Map> getPageByCategoryId(String categoryId, PageQuery pageQuery) {
        int count = sysUserMapper.countByCategoryId(categoryId);
        if (count > 0) {
            List<Map> list = sysUserMapper.getPageByCategoryId(categoryId, pageQuery);
            PageResult<Map> result = new PageResult<>();
            result.setList(list);
            Pagination pagination = new Pagination();
            pagination.setTotal(count);
            pagination.setPageSize(pageQuery.getPageSize());
            pagination.setCurrentPage(pageQuery.getPageNo());
            result.setPagination(pagination);
            return result;
        }
        return new PageResult<>();
    }

    /**
     * 根据用户名查询用户
     *
     * @param username 用户名
     * @return
     */
    @Override
    public Map findByUsername(String username) {
        return sysUserMapper.findByUsername(username);
    }

    /**
     * 修改用户状态
     *
     * @param id              用户id
     * @param status          修改后用的状态
     * @param currentUsername 当前用户
     */
    @Override
    public void updateStatusByUserId(Integer id, int status, String currentUsername) {
        Map params = new HashMap(4);
        params.put("status", status);
        params.put("lastupdTime", new Date());
        params.put("lastupdMan", currentUsername);
        sysUserMapper.updateStatusByUserId(id, params);
    }

    /**
     * 根据用户id查询用户
     *
     * @param id 系统用户id
     * @return
     */
    @Override
    public SysUser findById(Integer id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据用户类型查询用户
     *
     * @param categoryId 系统用户类型id
     * @return
     */
    @Override
    public List<SysUser> findByCategoryId(String categoryId) {
        return sysUserMapper.findByCategoryIdAndStatus(categoryId, UserConst.ENABLE);
    }

    /**
     * 重置密码
     *
     * @param id              系统用户id
     * @param currentUsername 当前用户
     */
    @Override
    public void resetPsw(Integer id, String currentUsername) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(id);
        if (sysUser == null) {
            throw new ParamException("该用户不存在，重置密码失败");
        }
        // TODO:
        String password = "123456";
        // 密码加密
        String encryptedPassword = Md5Util.encrypt(password);

        Map params = new HashMap(4);
        params.put("password", encryptedPassword);
        params.put("lastupdTime", new Date());
        params.put("lastupdMan", currentUsername);
        sysUserMapper.updatePasswordByUserId(id, params);
    }

    /**
     * 修改密码
     *
     * @param id              系统用户id
     * @param newPwd          新密码
     * @param currentUsername 当前用户
     */
    @Override
    public void updatePsw(Integer id, String newPwd, String currentUsername) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(id);
        if (sysUser == null) {
            throw new ParamException("该用户不存在，修改密码失败");
        }
        Map params = new HashMap(4);
        params.put("password", newPwd);
        params.put("lastupdTime", new Date());
        params.put("lastupdMan", currentUsername);
        sysUserMapper.updatePasswordByUserId(id, params);
    }

    /**
     * 根据社团id获取用户
     *
     * @param assId 社团id
     * @return
     */
    @Override
    public List<SysUser> findByAssId(Integer assId) {
        return sysUserMapper.findByAssIdAndStatus(assId, UserConst.ENABLE);
    }

    /**
     * 根据社团id禁用用户
     *
     * @param assId
     * @param currentUsername
     */
    @Override
    public void updateStatusByAssId(Integer assId, String currentUsername) {
        Map params = new HashMap(4);
        params.put("status", UserConst.DISABLE);
        params.put("lastupdTime", new Date());
        params.put("lastupdMan", currentUsername);
        sysUserMapper.updateStatusByAssId(assId, params);
    }
}
